import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/king/king_history_logic.dart';
import 'package:sports_new/entity/king/king_history_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/king/items/history_label.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';

import '../../entity/other/play_entity.dart';
import '../../utils/routes.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/loading/no_data_widget.dart';

class KingHistoryPage extends StatefulWidget {
  const KingHistoryPage({super.key});

  @override
  State<KingHistoryPage> createState() => _KingHistoryPageState();
}

class _KingHistoryPageState extends State<KingHistoryPage> {
  final KingHistoryLogic logic = Get.put(KingHistoryLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<KingHistoryLogic>(
      builder: (logic) {
        return Scaffold(
          appBar: Styles.appBar(title: QkdText("预测记录")),
          body: Container(
            color: Colours.greyF5F7FA,
            child: EasyRefresh.builder(
              controller: logic.refreshController,
              footer: Styles.refreshFooter(position: IndicatorPosition.locator),
              onLoad: logic.loadMore,
              childBuilder: (BuildContext context, ScrollPhysics physics) =>
                LoadingWidget<bool>(
                  isLoading: logic.data == null,
                  data: logic.data?.length == 0,
                  noData: const NoDataWidget(tip: "暂无记录，快去预测吧"),
                  child: () => ListView(
                    physics: physics,
                    children: List.generate(logic.data?.length ?? 0,
                      (index) => item(logic.data?[index])
                    ).append(const FooterLocator())
              ),
                )
            ),
          )
        );
      }
    );
  }

  Widget item(KingHistoryEntity? entity){
    return Block(
      cardStyle: const CardStyle(
        padding: EdgeInsets.fromLTRB(10,10,10,0),
        margin: EdgeInsets.fromLTRB(10,10,10,0)
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              QkdText(entity?.guessDate ?? "", fontSize: 15),
              const Spacer(),
              QkdText(entity?.scoreDate ?? "",
                fontSize: 12,color: Colours.main
              )
            ],
          ).paddingOnly(left: 6,right: 6,bottom: 8),
          ...List.generate(entity?.matchList?.length ?? 0,
            (index) => matchItem(entity?.matchList?[index])),
          if(entity?.scoreExt.hasValue == true)
          QkdText(entity?.scoreExt ?? "",
            fontSize: 12,color: Colours.main
          ).paddingSymmetric(vertical: 10,horizontal: 6)
        ]
      ),
    );
  }

  Widget matchItem(HistoryMatch? entity){
    String winText = "";
    List<String> winChoice = [];
    List<String> pointsChoice = [];
    List<String> winResult = [];
    List<String> pointsResult = [];
    if(entity?.item?.hasValue == true){
      decodePlayType(entity!.item!).forEach((element) {
        if(element.playType == playType["胜平负"]
            || element.playType == playType["让球胜平负"]) {
          winText = "主${element.handicap?.contains("-") == true?"":"+"}${element.handicap}: ";
          winChoice = element.choices ?? [];
        }else{
          pointsChoice = element.choices ?? [];
        }
      });
    }
    entity?.itemShowList?.forEach((element) {
      var e = decodePlayResult(element);
      if(e?.playType == playType["胜平负"]
        || e?.playType == playType["让球胜平负"]){
        winResult = e?.choices ?? [];
      }else{
        pointsResult = e?.choices ?? [];
      }
    });
    return GestureDetector(
      onTap: () => Get.toNamed(Routes.kingDetail, arguments: entity?.matchId),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Stack(
            alignment: AlignmentDirectional.center,
            children: [
              Container(
                width: Get.width,
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    color: Colours.greyF8),
                child: DefaultTextStyle(
                  style: const TextStyle(fontSize: 15,color: Colours.text),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      QkdText("【${entity?.leagueName ?? ""}】"
                        "${entity?.matchTime ?? ""} "
                        "${entity?.homeName ?? ""} "
                        "${formScore(entity?.homeScore, entity?.guestScore)} "
                        "${entity?.guestName ?? ""}",
                          fontSize: 15,
                          fontWeight: FontWeight.w500),
                      QkdText("您预测本场比赛"),
                      if(winChoice.isNotEmpty)
                      Text.rich(
                        TextSpan(
                          children: [
                            TextSpan(text: winText),
                            ...List.generate(winChoice.length, (index) =>
                              TextSpan(text: winChoice[index],
                                style: TextStyle(
                                  color: winResult.contains(winChoice[index])?
                                  Colours.main:Colours.text))
                            ).insertEvery(const TextSpan(text: "、"))
                            ]),
                        style: const TextStyle(fontSize: 15,color: Colours.text)),
                      if(pointsChoice.isNotEmpty)
                      Text.rich(
                        TextSpan(
                          children: [
                            const TextSpan(text: "双方进球之和："),
                            ...List.generate(pointsChoice.length, (index) =>
                              TextSpan(text: pointsChoice[index],
                                style: TextStyle(
                                  color: pointsResult.contains(pointsChoice[index])?
                                  Colours.main:Colours.text))
                            ).insertEvery(const TextSpan(text: "、"))
                          ]),
                          style: const TextStyle(fontSize: 15,color: Colours.text)),
                    ],
                  ),
                ),
              ),
              if(entity?.scoreStr.hasValue == true)
              Positioned(
                right: 10,bottom: 16,
                child: HistoryLabel.king(text: entity?.scoreStr ?? ""))
            ],
          ),
          Container(height: 10),
          QkdText("提交时间 ${entity?.createTime ?? ""}",
            fontSize: 12,color: Colours.grey99),
          Container(height: 10),
          const Divider(color: Colours.greyEE,height: 0.5)
        ]
      ),
    );
  }

  String formScore(String? home,String? guest){
    if(home != null && guest != null){
      return "$home:$guest";
    }else{
      return "vs";
    }
  }
}
